import $ from 'jquery';
import { jwtDecode } from 'jwt-decode';

const ModuleUser = {
  state: {
    id: "",
    username: "",
    photo: "",
    phone_number: "",
    consumer_address: "",
    access: "",
    refresh: "",
    is_login: false,
    is_superuser: false,
  },
  getters: {
  },
  mutations: {
      updateUser(state, user) {
          state.id = user.id;
          state.username = user.username;
          state.photo = user.photo;
          state.phone_number = user.phone_number;
          state.consumer_address = user.consumer_address;
          state.access = user.access;
          state.refresh = user.refresh;
          state.is_login = user.is_login;
          state.is_superuser = user.is_superuser;
      },
      updateAccess(state, access) {
          state.access = access;
      },
      logout(state) {
          state.id = "";
          state.username = "";
          state.photo = "";
          state.phone_number = "";
          state.consumer_address = "";
          state.access = "";
          state.refresh = "";
          state.is_login = false;
          state.is_superuser = false;
          localStorage.removeItem('UserAccess');  
          localStorage.removeItem('UserRefresh');  
          localStorage.removeItem('Access_Obj');
          localStorage.removeItem('id');  
          localStorage.removeItem('is_superuser');  
          localStorage.removeItem('phone_number');  
          localStorage.removeItem('photo');  
          localStorage.removeItem('username');
          localStorage.removeItem('consumer_address');
      }
  },
  actions: {
      login(context, data) {
        $.ajax({
            url: "http://47.121.28.202:8000/settings/token/",
            type: "POST",
            data: {
                username: data.username,
                password: data.password,
            },
            success(resp) {
                const {access, refresh} = resp;
                const access_obj = jwtDecode(access);
                localStorage.setItem('UserRefresh', refresh);
                localStorage.setItem('Access_Obj', JSON.stringify(access_obj));
                localStorage.setItem('UserAccess', access);
                setInterval(() => {
                    $.ajax({
                        url: "http://47.121.28.202:8000/settings/token/refresh/",
                        type: "POST",
                        data: {
                            refresh,
                        },
                        success(resp) {
                            context.commit('updateAccess', resp.access);
                        }
                    });
                }, 4.5 * 60 * 1000);
                $.ajax({
                    url: "http://47.121.28.202:8000/settings/getinfo/",
                    type: "GET",
                    data: {
                        user_id: access_obj.user_id,
                    },
                    headers: {
                        'Authorization': "Bearer " + access,
                    },
                    success(resp) {
                        localStorage.setItem('id', resp.id);
                        localStorage.setItem('is_superuser', resp.is_superuser);
                        localStorage.setItem('phone_number', resp.phone_number);
                        localStorage.setItem('photo', resp.photo);
                        localStorage.setItem('username', resp.username);
                        localStorage.setItem('consumer_address', resp.consumer_address);
                        context.commit("updateUser", {
                            ...resp,
                            access: access,
                            refresh: refresh,
                            is_login: true,
                        });
                        data.success();
                    },
                })
            },
            error() {
                data.error();
            }
        });
      },

      autoLogin({ commit }) {  
            const is_superuser = localStorage.getItem('is_superuser');
            const phone_number = localStorage.getItem('phone_number');
            const photo = localStorage.getItem('photo');
            const username = localStorage.getItem('username');
            const access = localStorage.getItem('UserAccess');  
            const refresh = localStorage.getItem('UserRefresh');  
            const accessObjStr = localStorage.getItem('Access_Obj');
            const consumer_address = localStorage.getItem('consumer_address'); 
            if (access && refresh && accessObjStr) {
                try {  
                    const accessObj = JSON.parse(accessObjStr); 
                    commit("updateUser", {  
                        id: accessObj.user_id,
                        access_obj: accessObj,
                        access: access,  
                        refresh: refresh,  
                        is_login: true,
                        is_superuser: is_superuser === 'true',
                        phone_number: phone_number,
                        photo: photo,
                        username: username,
                        consumer_address: consumer_address,   
                    }); 
                    // dispatch('startTokenRefresh', refresh); 
                } catch (error) {  
                    console.error("Error parsing stored access token:", error);  
                    localStorage.removeItem('UserAccess');  
                    localStorage.removeItem('UserRefresh');  
                    localStorage.removeItem('Access_Obj');  
                } 
            }
      }
  },
  modules: {
  }
};


export default ModuleUser;
